package core

import (
	"fmt"
	"os"
	"time"
)

// 定时任务日志清理
func startCleanupTask() {
	ticker := time.NewTicker(24 * time.Hour)
	for {
		select {
		case <-ticker.C:
			cleanupOldLogs()
		}
	}
}

func cleanupOldLogs() {
	dirs, err := os.ReadDir(LogDir)
	if err != nil {
		return
	}

	retention := time.Now().Add(-time.Duration(LogRetentionDays) * 24 * time.Hour)

	for _, dir := range dirs {
		if !dir.IsDir() {
			continue
		}

		path := fmt.Sprintf("%s/%s", LogDir, dir.Name())
		files, err := os.ReadDir(path)
		if err != nil {
			continue
		}

		for _, file := range files {
			if file.IsDir() {
				continue
			}

			fp := fmt.Sprintf("%s/%s", path, file.Name())
			info, err := os.Stat(fp)
			if err != nil {
				continue
			}

			if info.ModTime().Before(retention) {
				os.Remove(fp)
			}
		}
	}
}
